package com.jingge.home.controller;

import com.jingge.home.service.WxMsgHandlerService;
import com.jingge.home.util.codec.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;

/**
 * @author Yongxiang
 * @date 2025-06-04 14:05
 * @email 1158055613@qq.com
 */
@RestController
@Slf4j
public class WxMsgHandleController {
	@Autowired
	private WxMsgHandlerService service;

	@Value("${wechat.token}")
	private String token;

	/**
	 * 用SHA1算法生成安全签名
	 *
	 * @param token     票据
	 * @param timestamp 时间戳
	 * @param nonce     随机字符串
	 * @param encrypt   密文
	 * @return 安全签名
	 */
	public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws Exception {
		try {
			String[] array = new String[]{token, timestamp, nonce, encrypt};
			StringBuilder sb = new StringBuilder();
			// 字符串排序
			Arrays.sort(array);
			for (int i = 0; i < 4; i++) {
				sb.append(array[i]);
			}
			String str = sb.toString();
			// SHA1签名生成
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(str.getBytes());
			byte[] digest = md.digest();
			StringBuilder hexstr = new StringBuilder();
			String shaHex = "";
			for (byte b : digest) {
				shaHex = Integer.toHexString(b & 0xFF);
				if (shaHex.length() < 2) {
					hexstr.append(0);
				}
				hexstr.append(shaHex);
			}
			return hexstr.toString();
		} catch (Exception e) {
			log.error("验证异常", e);
		}
		return "";
	}

	@PostMapping(value = "/wechat", produces = "application/xml;charset=UTF-8")
	public String handleMsg(@RequestBody String requestBody, @RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce) {
		log.info("接收微信请求：[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n]", signature, timestamp, nonce, requestBody);
		WxCpXmlMessage inMessage = WxCpXmlMessage.fromXml(requestBody, null);
		log.info("消息内容：{}", JsonUtil.pojoToJsonString(inMessage));
		String msg = service.routeMessage(inMessage);
		log.info("回执消息：{}", msg);
		return msg;
	}

	@GetMapping("/wechat")
	public void weChatTestV(HttpServletRequest request, HttpServletResponse response) {
		// 1、验证消息的确来自微信服务器
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		log.info("接收微信验证请求：[signature=[{}], timestamp=[{}], nonce=[{}], echostr=[{}]", signature, timestamp, nonce, echostr);
		//将微信echostr返回给微信服务器
		try (OutputStream os = response.getOutputStream()) {
			String sha1 = getSHA1(token, timestamp, nonce, "");
			//和signature进行对比
			if (sha1.equals(signature)) {
				// 返回echostr给微信
				os.write(URLEncoder
						.encode(echostr, "UTF-8")
						.getBytes());
				os.flush();
			}
		} catch (Exception e) {
			log.error("验证异常", e);
		}
	}

}
